import React, { useState } from 'react';
import { Popconfirm, message } from 'antd';

/**
 * 保存按钮二次确认
 * onConfirm 点击弹窗保存后的回调函数
 * confirmVisible 传递给组件的 Promise<boolean>，true是不弹窗；false是展示弹窗
 */
const ButtonConfirm = ({ children, onConfirm, confirmVisible }) => {
    const [popConfirmVisible, setPopConfirmVisible] = useState();

    const confirmCallback = () => {
        if (onConfirm) {
            onConfirm();
            setPopConfirmVisible(false);
        }
    };

    const handleClick = async () => {
        if (confirmVisible && typeof confirmVisible === 'function') {
            try {
                const result = await confirmVisible();
                if (result) {
                    confirmCallback();
                }
                setPopConfirmVisible(!result);
            } catch (error) {
                message.error(error);
            }
        }
    };

    return (
        <React.Fragment>
            <Popconfirm
                trigger="click"
                arrowPointAtCenter
                title={
                    <>
                        存在已保存内容，确定继续保存？
                        <br />
                        <span style={{ fontSize: 12, color: '#F04134' }}>继续保存将覆盖已保存内容</span>
                    </>
                }
                onCancel={() => setPopConfirmVisible(false)}
                getPopupContainer={node => node}
                visible={popConfirmVisible}
                onConfirm={confirmCallback}
                okText="继续保存"
            >
                <div onClick={handleClick}>{children}</div>
            </Popconfirm>
        </React.Fragment>
    );
};

export default ButtonConfirm;
